# @author: Yxinmiracle
# @project: Python_w
# @file: font.py
# @time: 2020/5/16 10:47

# https://www.w3school.com.cn/xmldom/dom_element.asp

import requests as r
from lxml import etree
import re
import base64
from fontTools.ttLib import TTFont # 操作字体文件
from xml.dom.minidom import parse # 解析xml文件
from io import BytesIO

TTF_FILE_NAME = 'font_58.woff'
XML_FILE_NAME = 'movie.xml'

rule = re.compile("&#x.*?;")

font_dict = {
    (0,410)      :0,
    (-888, 0)    :1,
    (-942, 0)    :2,
    (159, -123)  :3,
    (-198, 0)    :4,
    (156, -102)  :5,
    (-121, 62)   :6,
    (-606, -1481):7,
    (-277, 129)  :8,
    (128, -74)   :9,
}

headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36',
}

url = "https://sz.58.com/chuzu/?PGTID=0d200001-0000-4ae6-d84a-bb7dbe4393f3&ClickID=1"

html = r.get(url,headers=headers)
html_text = html.text

# 从不经过解码的源代码中提取base64加密后的编码
font_encoded_data = re.search('base64,(.*?)\)', html_text, re.S).group(1)
font_decoded_data = base64.b64decode(font_encoded_data)


with open(TTF_FILE_NAME, 'wb') as fp:
    fp.write(font_decoded_data)

fonts = TTFont(TTF_FILE_NAME)
fonts.saveXML(XML_FILE_NAME)


tf = TTFont(BytesIO(font_decoded_data))

glyph_dict = {}
for i in tf.getGlyphNames()[1:]:
    x1,y1 = tf["glyf"][i].coordinates[0][0],tf["glyf"][i].coordinates[0][1]
    x2,y2 = tf["glyf"][i].coordinates[1][0],tf["glyf"][i].coordinates[1][1]
    new=(x2-x1,y2-y1)
    glyph_dict[i] = new

"""
接下来是解析xml文件
"""
# 读取文件
dom = parse('movie.xml')

# 获取文档元素对象
data = dom.documentElement
# 获取 map中code值
stus = data.getElementsByTagName('cmap_format_4')[0]
maps = stus.getElementsByTagName('map')
xml_dict = {}
for map in maps:
    xml_dict[map.getAttribute("code").replace("0x","&#x")+';'] = map.getAttribute("name")

replaceStringList = re.findall(rule,html_text)

for replaceString in replaceStringList:
    if replaceString in xml_dict:
        glyphName = xml_dict[replaceString]
        location = glyph_dict[glyphName]
        result = font_dict[location]
        html_text = re.sub(replaceString,str(result),html_text)


tree = etree.HTML(html_text)

lis = tree.xpath('//ul[@class="house-list"]/li')

for li in lis:
    try:
        href = li.xpath('div[2]/h2/a/@href')[0]
        money = li.xpath('div[@class="list-li-right"]/div[2]/b/text()')[0]
        print(href,money)
    except:
        pass
        # print(f"{href} have error")


